
#include "UDPHelper.h"
/*
 * 开始工作：输入端口号  开始监听
 * 接收：监听端口  收到消息进行校验 成功后保存socket 并刷新显示文本框及客户端socket列表
 * 发送：从客户端Socket列表选中一个目标  完成ip和端口号的绑定  发送数据
 */

UDPHelper::UDPHelper(QWidget *parent) //构造函数
    : QMainWindow(parent)
{
    //窗口大小设定
    this->setWindowTitle(tr("上位机")); //继承类属性
    this->resize(700, 450);
    this->setMinimumSize(640, 480);
    this->setMaximumSize(640, 480);

    initUi();

    connect(listenBtnPtr, &QPushButton::clicked, this, &UDPHelper::startListen);                    //对象，信号，当前窗口，执行槽函数
    connect(clearRecTextButton, &QPushButton::clicked, this, [=]() { recListWidgetPtr->clear(); }); //lambda表达式
    // connect(openLinkBtn, &QPushButton::clicked, this, [=](){
    //     if(this->recListWidgetPtr->currentRow() >= 0)//大于等于0，相当于选中，未选中默认-1
    //         QDesktopServices::openUrl(QUrl(this->recListWidgetPtr->currentItem()->text()));
    //     else
    //         QMessageBox::warning(this, "警告", "请选中一个有效网址！！！", QMessageBox::Yes);
    // });
    qDebug() << "Create UDPHelper" << endl;
}

UDPHelper::~UDPHelper()
{
    if (listenBtnPtr->text() == tr("停止监听"))
    {
        disconnect(recSocket, &QUdpSocket::readyRead, this, &UDPHelper::readData);
        delete recSocket;
    }
    destroyUI();
}

void UDPHelper::startListen(void)
{
    if (listenBtnPtr->text() == tr("开始监听"))
    {
        recSocket = new QUdpSocket(this);
        serverPort = this->portLineEditPtr->text().toInt();
        recSocket->bind(QHostAddress::AnyIPv4, serverPort); //开始监听端口，存IP和端口号到套接字中
    connect(recSocket, &QUdpSocket::readyRead, this, &UDPHelper::readData);
        listenBtnPtr->setText(tr("停止监听"));      //文字设置
        qDebug() << "开始监听端口：" << serverPort; //debug显示的东西
    }
    else
    {
    disconnect(recSocket, &QUdpSocket::readyRead, this, &UDPHelper::readData);
        delete recSocket;
        listenBtnPtr->setText(tr("开始监听"));
    }
}

void UDPHelper::readData()
{
    QByteArray array;                                                     //字节流
    QHostAddress address;                                                 //IP地址
    quint16 port;                                                         //端口
    array.resize(recSocket->bytesAvailable());                            //返回一个常数，XX字节的数据
    recSocket->readDatagram(array.data(), array.size(), &address, &port); //读数据包里的东西
    //进行校验 添加client socket
    // qDebug() << address.toString()+":"+QString::number(port);
    // qDebug() << array.size() << "   " << (quint8)array.data()[array.size()-1] << endl;

    // qDebug() << array.data() << endl;
    // if(array.data()[array.size()-1] == array.size()){
    //     array.remove(array.size()-1,1);
    //     sendAckUDP(address, port);
    //     if(this->recListWidgetPtr->count() == 0 || this->recListWidgetPtr->item(this->recListWidgetPtr->count()-1)->text() != array.data())
    //         this->recListWidgetPtr->addItem(array);
    // }
}

void UDPHelper::initUi()
{
    portLabelPtr = new QLabel(this); //申请Qlabel大小的空间
    portLabelPtr->setText("端口号：");
    portLabelPtr->setGeometry(30, 30, 60, 20); //横纵坐标，长宽

    portLineEditPtr = new QLineEdit(this);
    portLineEditPtr->setText(tr("7000"));
    portLineEditPtr->setGeometry(100, 30, 60, 20);

    listenBtnPtr = new QPushButton(this);
    listenBtnPtr->setText("开始监听");
    listenBtnPtr->setGeometry(180, 30, 60, 20);

    recTextLabelPtr = new QLabel(this);
    recTextLabelPtr->setText("接收信息:");
    recTextLabelPtr->setGeometry(30, 80, 60, 20);

    recListWidgetPtr = new QListWidget(this);
    recListWidgetPtr->setGeometry(100, 80, 480, 320);

    // openLinkBtn = new QPushButton(this);
    // openLinkBtn->setText("打开选中链接");
    // openLinkBtn->setGeometry(450,410,100,20);\

    clearRecTextButton = new QPushButton(this);
    clearRecTextButton->setText("清空信息");
    clearRecTextButton->setGeometry(100, 410, 80, 20);
}

void UDPHelper::sendAckUDP(QHostAddress ipAddr, quint16 port)
{
    sendSocket = new QUdpSocket(this);
    sendSocket->writeDatagram(ackStr.toUtf8(), ipAddr, port);
    delete sendSocket;
}

void UDPHelper::destroyUI()
{
    delete portLabelPtr;
    delete portLineEditPtr;
    delete listenBtnPtr;
    delete recTextLabelPtr;
    delete recListWidgetPtr;
    //    delete openLinkBtn;
    delete clearRecTextButton;
    qDebug() << "destroy UDPHelper UI" << endl;
}
